<script setup lang='ts'>
import { useMainStore } from '@/store/index'
import { useMainLogin } from '@/store/user'
import { onMounted, ref, watch, watchEffect } from 'vue'
import * as mars3d from "mars3d"
import type { qie } from 'element-plus'
import { Tree } from '@/types/serviceAddress'
import chooseNode from '@utils/chooseTreeNode.ts'
import { trueUrl } from '@utils/resetUrl'
import { getRoadImageListRoad,getRoadImageList } from '@/api/grid/index'
import { ElMessage } from 'element-plus'

const store = useMainStore()
const user = useMainLogin()
const qie = ref<qie>()
const treeExpandelKeys = ref<any>([])
const filterText = ref<string>('')
// 树结构
const dataSource = ref<any>()
const props = ref<any>({isLeaf: 'leaf'})

onMounted(async () => {
  // 目标节点
  const targetNode = document.getElementById('listBox8');
  let height = targetNode.offsetHeight;
  let top2Bottom = window.innerHeight - targetNode.getBoundingClientRect().top -10
 // 创建一个 MutationObserver 实例
 const observer = new MutationObserver((mutationsList, observer) => {
   // 在每次 DOM 变化时触发的回调函数
   for (let mutation of mutationsList) {
     if (mutation.type === 'attributes'&& targetNode.offsetHeight!=height) {
      if(targetNode.offsetHeight < top2Bottom) {
        targetNode.style.top = '0px'
      }else {
        targetNode.style.top = (top2Bottom - targetNode.offsetHeight - 10) + 'px'
      }
     }
   }
 });

 // 配置 MutationObserver
 const config = { childList: true, attributes: true, subtree: true };

 // 开始观察目标节点
 observer.observe(targetNode, config);
})

/* 树型 */
// 搜索
watch(filterText, (val) => {
  qie.value!.filter(val)
})

const filterNode = (value: string, data: Tree, node: any) => {
  if (!value) return true
  return chooseNode(value, data, node)
}


// 懒加载根节点
const loadNode = async (node,resolve) => {
  if(node.level == 0) {
    await loadTree(resolve)
  }else if(node.level == 1) {
    var folderId = node.data.folderId
    await loadTree2(resolve,folderId)
  }else {
    var folderId = node.data.folderId
    getRoadImageList({folderId:folderId}).then(res=>{
      if(res.code === 200) {
        res.rows.forEach((item,index) => {
          item.leaf = true
          let zIndex = item.zIndex = res.rows.length - index
          if (item.isOpen && !window.map.getLayerById(item.id)) {
            let url = resetLayerUrl(item.imageUrl)
            loadEntity(url,zIndex,item.imageId)
          }
        })
        resolve(res.rows)
      }
    })
  }
}

// 懒加载子节点
const loadTree = async (resolve) => {
  // 等待用户信息加载完成
  if (!user.userId) {
    await new Promise(resolve => {
      const unwatch = watch(() => user.userId, (newVal) => {
        if (newVal) {
          unwatch()
          resolve(true)
        }
      }, { immediate: true })
    })
  }

  try {
    const res = await getRoadImageListRoad({userId: user.userId, parentId: 0,type:'切片',orderByColumn:"update_time",isAsc:"desc"})
    if(res.code === 200) {
      if(res.rows.length > 0) {
        res.rows.forEach(item => {
          item.isOpen ? treeExpandelKeys.value.push(item.folderId) : ''
          item.id = item.folderId
          item.children = []
        })
        resolve(res.rows)
      }
    }
  } catch (error) {
    console.error('Failed to load road image list:', error)
    ElMessage.error('加载道路影像列表失败')
  }
}

// 懒加载子节点
const loadTree2 = async (resolve,folderId) => {
  // 等待用户信息加载完成
  if (!user.userId) {
    await new Promise(resolve => {
      const unwatch = watch(() => user.userId, (newVal) => {
        if (newVal) {
          unwatch()
          resolve(true)
        }
      }, { immediate: true })
    })
  }

  try {
    const res = await getRoadImageListRoad({userId: user.userId, parentId: folderId,type:'切片',orderByColumn:"name",isAsc:"asc"})
    if(res.code === 200) {
      if(res.rows.length > 0) {
        res.rows.forEach(item => {
          item.isOpen ? treeExpandelKeys.value.push(item.folderId) : ''
          item.id = item.folderId
          item.children = []
        })
        resolve(res.rows)
      }
    }
  } catch (error) {
    console.error('Failed to load road image list:', error)
    ElMessage.error('加载道路影像列表失败')
  }
}

// 加载实例
const loadEntity = async (imageUrl, zIndex, imageId) => {
  try {
    const response = await fetch(imageUrl + '/meta.json')
    const data = await response.json()
    // 加载切片
    const layer = new mars3d.layer.XyzLayer({
        id:imageId,
        url: imageUrl + "/{z}/{x}/{y}.png",
        rectangle: {
            xmin: data.bounds.west,
            xmax: data.bounds.east,
            ymin: data.bounds.south,
            ymax: data.bounds.north,
        },
        tms: true,
    })

    window.map.addLayer(layer)
    layer.zIndex = zIndex
  } catch (error) {
    console.log("加载meta.json失败", error)
  }
}

const change = async (data, self, childSelect) => {
  if (data.imageId) {
    data.isOpen = self
    data.isDelOss = 1
    if (!window.map.getLayerById(data.imageId)) {
      let url = resetLayerUrl(data.imageUrl)
      await loadEntity(url,data.zIndex,data.imageId)
    } else {
      window.map.getLayerById(data.imageId).show = self
    }
  } else {
    data.isOpen = self || childSelect ? true : false
  }
}

// 修改url
const resetLayerUrl = (url:any) => {
  var arr = []
  var urlstr = ''
  if(url.indexOf('zxchhwy')>0 || url.indexOf('zxchjfj')>0 || url.indexOf('zxchjfn')>0 || url.indexOf('zxchjf')>0){
    return url
  }
  if(url.indexOf('zxch.cpolar.cn') > 0){
    arr = url.split('zxch.cpolar.cn')
    urlstr = '/zxchhwy' + arr[1]
  }
  else if(url.indexOf('139.9.173.189:8090') > 0){
    arr = url.split('139.9.173.189:8090')
    urlstr = '/zxchjfj' + arr[1]
  }
  else if(url.indexOf('139.9.173.189:8091') > 0){
    arr = url.split('139.9.173.189:8091')
    urlstr = '/zxchjfn' + arr[1]
  }
  else if(url.indexOf('139.9.173.189:8080') > 0){
    arr = url.split('139.9.173.189:8080')
    urlstr = '/zxchjf' + arr[1]
  }else{
    ElMessage({
      type: 'warning',
      message: '该资源禁止上传!'
    });
    return false
  }
  return urlstr
}

// 相机移动至要素
const flyToGraphic = (data) => {
  window.map.flyToGraphic(window.map.getLayerById(data.imageId),{radius:4000})
}
</script>

<template>
<!-- 影像 -->
  <div class="TabbarBtn">
    <el-tooltip
      class="box-item"
      effect="dark"
      content="道路影像"
      placement="left"
    >
    <div :class="store.activeBtn==5?'iconBox show':'iconBox'" @click="store.activeBtn==5?store.activeBtn=0:store.activeBtn=5">
      <img src="@/assets/image/qie.png" alt="">
    </div>
    </el-tooltip>
    <div :class="store.activeBtn==5?'btnTooltip show':'btnTooltip'" id="listBox8">
      <span class="listBox" id="seventh-element-introduction">
        <i @click="store.activeBtn=0" class="iconfont icon-cuo" style="position: absolute;right: 10px; top: 10px;cursor: pointer;"></i>
        <div style="clear: both;padding: 30px 0 10px 0;" class="grid-tree">
          <el-input v-model="filterText" placeholder="请输入名称搜索" />
          <!-- 树型 -->
          <el-scrollbar>
            <el-tree
              ref="qie"
              :props="props"
              :data="dataSource"
              node-key="id"
              show-checkbox
              draggable
              lazy
              :load="loadNode"
              @check-change="change"
              :default-expanded-keys="treeExpandelKeys"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
            >
              <template #default="{ node, data }">
                  <div v-if="node.level == 1">
                    <div class="treeNode">
                      <span class="tree1Title">{{ data.name }}</span>
                    </div>
                  </div>
                  <div v-else-if="node.level == 2">
                    <div class="treeNode">
                      <span class="tree1Title">{{ data.name }}</span>
                    </div>
                  </div>
                  <div v-else>
                    <div class="treeNode">
                      <span class="tree1Title">{{ data.pileNumberRange }}</span>

                      <div style="display: flex;align-items: center;">
                        <img @click.stop="flyToGraphic(data)" style="width: 16px;margin-left: 5px;" src="@/assets/image/dingwei.png" alt="">
                      </div>

                    </div>
                  </div>
              </template>
          </el-tree>
          </el-scrollbar>
        </div>
      </span>
    </div>
  </div>

</template>

<style scoped>
/* 服务地址 */
.addFrom {
  padding: 10px 20px;
}
.slider-demo-block {
  display: flex;
  align-items: center;
}
.slider-demo-block .el-slider {
  margin-top: 0;
}
.slider-demo-block .demonstration {
  font-size: 14px;
  color: #fff;
  line-height: 44px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-bottom: 0;
  width: 60px;
}
.slider-demo-block .demonstration + .el-slider {
  flex: 0 0 70%;
}
.submit {
  text-align: center;
}
.submit span{
  display: inline-block;
  padding: 6px 24px;
  border-radius: 10px;
  background: #3DBDA7;
  color: #fff;
  cursor: pointer;
  user-select: none;
}
</style>
<style>
.grid-tree .el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content {
    background-color: #666 !important;
}
</style>
